package pl.edu.agh.iosr.gamblingzone.action;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import static org.jboss.seam.ScopeType.SESSION;
import pl.edu.agh.iosr.gamblingzone.dao.UserDAO;
import pl.edu.agh.iosr.gamblingzone.model.User;
import pl.edu.agh.iosr.gamblingzone.utils.DAOFactory;

/**
 * This is examplary code. It works, but it needs some improvements :D
 * 
 * @author maciej
 */

@Stateless
@Name("authenticator")
public class MyAuthenticatorAction implements MyAuthenticator {

	/** The log. */
	@Logger
	Log log;
	
	/** The em. */
	@PersistenceContext
	EntityManager em;
	
	@In(required=true)
	DAOFactory dao;

	/** The identity. */
	@In
	Identity identity;

	/** The user. */
	@Out(required = false, scope = SESSION)
	private User user;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyAuthenticator#authenticate()
	 */
	public boolean authenticate() {
		UserDAO userDAO = dao.getUserDAO();

		if (!userDAO.authenticateUser(identity.getUsername(), identity
				.getPassword())) {
			log.info("Authenticate #0", "Wrong user: " + identity.getUsername()
					+ " or password: " + identity.getPassword());
			return false;
		} else {
			log.info("Authenticate #0", identity.getUsername()
					+ " successfully authorized " + identity.getPassword());

			user = userDAO.findByLogin(identity.getUsername());

			log.info("user retrievede #0", user.getLoginName() + " | "
					+ user.getPassword());
			
			if (user.getRoles() != null) {
				for (String role : user.getRoles()) {
					identity.addRole(role);
				}
			}

			return true;
		}
	}
}
